package com.huatai.vba.execute.action;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.huatai.vba.common.utils.*;
import com.huatai.vba.dal.jdbc.DBUtils;
import com.huatai.vba.dal.jdbc.SqlUtils;
import com.huatai.vba.dal.model.VbaFileAction;
import com.huatai.vba.execute.action.vo.Hsfundid;
import com.huatai.vba.execute.action.vo.Qsjs_tmp;
import com.huatai.vba.properties.Dbconfig;

/**
 * 生成qsjs
 * 
 * @author fanrui16
 *
 */
@Service("icbcCreateQsjsActionExecutor")
public class IcbcCreateQsjsActionExecutor extends AbstractIcbcActionExecutor {

	@Override
	public void execute(VbaFileAction action) {
		try {
			getQsjsTrasData();
			doQsjs_new();
		} catch (Exception e) {
			logger.error("系统异常", e);
		}

	}

	public void doQsjs_new() throws Exception {
		String pstrSjsRepo = this.getRepoCode("SZ");
		String tmpSql = "delete from qsjs_tmp ";
		vbaExtendsService.executeSql(tmpSql);

		// 复制数据
		tmpSql = "insert into qsjs select * from qsjs_tmp";
		vbaExtendsService.executeSql(tmpSql);

		// '深交所数据生成

		String gddmzmQsjs, hslxQsjs, ywlbQsjs;
		Integer lngHBCJHM = 1;
		tmpSql = " select * from sjsmx1 ";

		List<Map<String, Object>> list = vbaExtendsService.querySql(tmpSql);
		for (Map<String, Object> map : list) {
			// '明细库里不再有cjhm，暂采用流水号递增
			String tmp_HBCJHM = lngHBCJHM + "";
			lngHBCJHM = lngHBCJHM + 1;

			String tmp_HBZQDM = (String) map.get("mxZQDM".toUpperCase());
			// '回报库的合同序号=6位mxjydy（交易单元） + 8位mxcjrq成交日期日期 + 8位 mxddbh
			String tmp_HBHTXH = (String) map.get("mxjydy".toUpperCase()) + (String) map.get("mxCJRQ".toUpperCase())
					+ (String) map.get("mxddbh".toUpperCase());

			// '股东代码 mxzqdh 证券帐号
			String tmp_HBGDDM = (String) map.get("mxzqzh".toUpperCase());

			// '成交数量 MXCJSL
			Integer tmp_HBCJSL = Math.abs(Integer.valueOf(map.get("mxCJSL".toUpperCase()) + ""));
			// '成交价格
			Double tmp_HBCJJG = Math.abs(Double.valueOf(map.get("mxCJJG".toUpperCase()) + ""));
			// '对方席位 MXZXBH的前6位
			String tmp_HBDFXW = Left(CStr(map.get("MXZXBH".toUpperCase())), 6);
			String tmp_HBDFGD = Right(CStr(map.get("MXZXBH".toUpperCase())), 10);
			String tmp_HBCJRQ = DateUtils.generalDate(CStr(map.get("mxCJRQ".toUpperCase())), "yyyyMMdd", "yyyy-MM-dd");
			String tmp_MXYWLB = CStr(map.get("MXYWLB"));
			String tmp_HBYWLB = getHbywlb(tmp_MXYWLB, Double.valueOf(map.get("MXSFJE".toUpperCase()) + ""));

			String tmp_GDDMZM = null, tmp_HSLX = null;
			if (pstrSjsRepo.indexOf(tmp_HBZQDM) >= 0 && tmp_HBCJSL == 0) {
				String tmp_HBCJHM_str = tmp_HBDFXW + tmp_HBDFGD;
				tmp_GDDMZM = CStr(Trim(getCombId(tmp_HBCJHM_str, tmp_HBYWLB, "2")));
				tmp_HSLX = "3";
				hslxQsjs = "3";
			} else {
				tmp_GDDMZM = CStr(Trim(getCombId(tmp_HBDFXW + tmp_HBDFGD, tmp_HBYWLB, "2")));
				tmp_HSLX = CStr(getHSLZ(tmp_HBDFXW + tmp_HBDFGD, tmp_HBYWLB, "2"));
				if ("777101".equals(tmp_GDDMZM) || "777102".equals(tmp_GDDMZM) || "777103".equals(tmp_GDDMZM)) {
					tmp_HSLX = "3";
				}
				hslxQsjs = tmp_HSLX;
			}
			gddmzmQsjs = tmp_GDDMZM;
			if (tmp_GDDMZM.length() > 0) {
				ywlbQsjs = getYwlbQsjs(tmp_HBYWLB, pstrSjsRepo, tmp_HBZQDM, tmp_HBCJSL);
				// '数量价格不为0 才插入
				if (StringUtils.isNotBlank(ywlbQsjs)) {
					if (tmp_HBCJJG != 0) {
						if (StringUtils.isBlank(tmp_HSLX))
							tmp_HSLX = "1";

						Qsjs_tmp qsjs_tmp = new Qsjs_tmp();
						qsjs_tmp.setCjrq(convertDateFormat(tmp_HBCJRQ));
						qsjs_tmp.setCjbh(tmp_HBCJHM);
						qsjs_tmp.setSqbh(Right(tmp_HBHTXH, 8));
						qsjs_tmp.setYwlb(ywlbQsjs);
						qsjs_tmp.setJjdm(gddmzmQsjs);
						qsjs_tmp.setJjmc(gddmzmQsjs);
						qsjs_tmp.setZhbh(gddmzmQsjs);
						qsjs_tmp.setScdm("2");
						qsjs_tmp.setZqdm(tmp_HBZQDM);
						qsjs_tmp.setGddm(tmp_HBGDDM);
						qsjs_tmp.setJyxw(Left(tmp_HBHTXH, 6));
						qsjs_tmp.setCjsl(tmp_HBCJSL);
						qsjs_tmp.setCjjg(tmp_HBCJJG);
						qsjs_tmp.setCjje(new BigDecimal(tmp_HBCJSL).multiply(new BigDecimal(tmp_HBCJJG)).doubleValue());
						qsjs_tmp.setBz(hslxQsjs);
						tmpSql = SqlUtils.generateSql(qsjs_tmp);
						vbaExtendsService.executeSql(tmpSql);
					}
				}
			}
		}

		// '上交所数据插入
		String combi = convertSql(strSeven);
		tmpSql = " select a.vc_seat_id ";
		tmpSql = tmpSql + " from ttradeseat a ,tfundinfo b ";
		tmpSql = tmpSql + " where a.l_fund_id = b.l_fund_id ";
		tmpSql = tmpSql + " and a.c_market_no = '1' ";
		tmpSql = tmpSql + " and a.c_trade = '1' ";
		tmpSql = tmpSql + " and vc_fund_code = any(" + strSeven + " )";
		tmpSql = tmpSql + " group by   a.vc_seat_id";
		list = DBUtils.executeQuery(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user), tmpSql);
		String[] arrSeatID = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			arrSeatID[i] = (String) list.get(i).get("vc_seat_id".toUpperCase());
		}
		for (String strSeatID : arrSeatID) {
			File f = new File(baseFilePath + "gh" + strSeatID + ".dbf");
			if (f.exists()) {
				tmpSql = "select GDDM,GDXM,BCRQ,CJBH,GSDM,CJSL,BCYE,ZQDM,SBSJ,CJSJ,CJJG,CJJE,SQBH,BS,MJBH from GH"
						+ strSeatID;
				List<Map<String, Object>> resultList = vbaExtendsService.querySql(tmpSql);
				for (Map<String, Object> map : resultList) {
					Qsjs_tmp qsjs_tmp = new Qsjs_tmp();
					gddmzmQsjs = "";
					String tmp_GDDM = CStr(map.get("GDDM"));
					String tmp_BCRQ = CStr(map.get("BCRQ"));
					String tmp_CJBH = CStr(map.get("CJBH"));
					String tmp_GSDM = CStr(map.get("GSDM"));
					String tmp_ZQDM = CStr(map.get("ZQDM"));
					Integer tmp_CJSL = Integer.valueOf(map.get("CJSL") + "");
					Double tmp_CJJG = Double.valueOf(map.get("CJJG") + "");
					Double tmp_CJJE = Double.valueOf(map.get("CJJE") + "");
					String tmp_SQBH = CStr(map.get("SQBH"));
					String tmp_BS = CStr(map.get("BS"));
					String tmp_GDDMZM = "888880".equals(tmp_ZQDM) ? Trim(getCombId(tmp_CJBH))
							: Trim(getCombId(tmp_CJBH, tmp_BS, "1"));
					gddmzmQsjs = tmp_GDDMZM;
					if (StringUtils.isNotBlank(tmp_GDDMZM) && combi.indexOf(gddmzmQsjs) >= 0) {

						tmpSql = " select B.VC_FUND_CODE,B.VC_FUND_NAME , A.*";
						tmpSql = tmpSql + " from tuncompletelog a";
						tmpSql = tmpSql + " INNER JOIN TFUNDINFO B ON B.L_FUND_ID = A.L_FUND_ID";
						tmpSql = tmpSql + " where a.vc_stockholder_id = '" + tmp_GDDM + "'";
						tmpSql = tmpSql + " and a.vc_inter_code like '7%" + Right(tmp_ZQDM, 3) + "SS'";
						tmpSql = tmpSql + " and (l_trade_date <= " + tmp_BCRQ;
						tmpSql = tmpSql + " and l_complete_date > = " + tmp_BCRQ + ")";

						resultList = DBUtils.executeQuery(Dbconfig.FATADB, user, Dbconfig.getPasswordByUserId(user),
								tmpSql);
						if (ListUtils.isNotEmpty(resultList)) {
							String strFundid = (String) resultList.get(0).get("vc_fund_code".toUpperCase());
							tmp_GDDMZM = getICBCCombi(strFundid);
						}

					}
					String tmp_HSLX = CStr(getHSLZ(tmp_CJBH, tmp_BS, "1"));
					// '投联账户的所有类型默认为1
					if ("777101".equals(tmp_GDDMZM) || "777102".equals(tmp_GDDMZM) || "777103".equals(tmp_GDDMZM)) {
						tmp_HSLX = "3";
						hslxQsjs = tmp_HSLX;
					}
					// '所有回购的投资分类强制为1 204001,202001
					if ("20".equals(Left(tmp_ZQDM.trim(), 2))) {
						tmp_HSLX = "3";
					}
					// '只要找到了组合代码，就插入
					if (combi.indexOf(gddmzmQsjs) >= 0) {
						if ("20".equals(Left(tmp_ZQDM.trim(), 2))) {
							if ("B".equals(tmp_BS)) {
								ywlbQsjs = "04";
							} else {
								ywlbQsjs = "03";
							}
						} else {
							if ("B".equals(tmp_BS)) {
								ywlbQsjs = "01";
							} else {
								ywlbQsjs = "02";
							}
						}
						// '除去股票，基金，所有的债券回购的数量放大10倍
						if (!("6".equals(Left(tmp_ZQDM, 1)) || "0".equals(Left(tmp_ZQDM, 1))
								|| "3".equals(Left(tmp_ZQDM, 1)) || "5".equals(Left(tmp_ZQDM, 1))
								|| "7".equals(Left(tmp_ZQDM, 1)))) {
							tmp_CJSL = tmp_CJSL + 10;
						}
						if (tmp_CJSL != 0 && tmp_CJJG.doubleValue() != 0) {
							qsjs_tmp.setCjrq(convertDateFormat(tmp_BCRQ));
							qsjs_tmp.setCjbh(tmp_CJBH);
							qsjs_tmp.setSqbh(tmp_SQBH);
							qsjs_tmp.setYwlb(ywlbQsjs);
							qsjs_tmp.setJjdm(gddmzmQsjs);
							qsjs_tmp.setJjmc(gddmzmQsjs);
							qsjs_tmp.setZhbh(gddmzmQsjs);
							qsjs_tmp.setScdm("1");
							qsjs_tmp.setZqdm(tmp_ZQDM);
							qsjs_tmp.setGddm(tmp_GDDM);
							qsjs_tmp.setJyxw(tmp_GSDM);
							qsjs_tmp.setCjsl(tmp_CJSL);
							qsjs_tmp.setCjjg(tmp_CJJG);
							qsjs_tmp.setCjje(tmp_CJJE);
							qsjs_tmp.setBz(tmp_HSLX);
							qsjs_tmp.executeInsert(vbaExtendsService);
						}
					}

				}
			}
		}
	}

	private void getQsjsTrasData() throws Exception {
		String combi = convertSql(strSeven);
		String sql = " delete from hsfundid ";
		vbaExtendsService.executeSql(sql);
		String strSql = " select a.vc_deal_no deal_id,b.vc_fund_code fund_code,a.vc_report_seat seat,c.c_invest_type,";
		strSql = strSql + " (case when d.c_market_no = '2' and d.c_entrust_direction = '5' then";
		strSql = strSql + " '0S' when d.c_market_no = '2' and d.c_entrust_direction = '6' then";
		strSql = strSql + " '0B' Else D.VC_report_direction end) vc_report_direction, ";
		strSql = strSql + " d.c_market_no ";
		strSql = strSql + " from TREALDEAL a, Tfundinfo b, tentrusts c,tentrustdirection d";
		strSql = strSql + " where a.l_fund_id = b.l_fund_id And c.l_entrust_serial_no = a.l_entrust_serial_no";
		strSql = strSql + " and a.c_market_no=d.c_market_no and a.c_entrust_direction=d.c_entrust_direction";
		strSql = strSql + "    and b.vc_fund_code in (" + combi + ") order by deal_id asc";
		List<Map<String, Object>> list = vbaExtendsService.querySql(strSql);
		for (Map<String, Object> map : list) {
			Hsfundid hs = new Hsfundid();
			String tmp_id = (String) map.get("DEAL_ID");
			String tmp_code = (String) map.get("FUND_CODE");
			String tmp_seat = (String) map.get("SEAT");
			String tmp_Code_t = getICBCCombi(tmp_code);

			if (tmp_seat.length() > 6) {
				if (tmp_id.length() < 8) {
					tmp_id = StringUtil.alignRights(tmp_id, 8, "0");
				}
			}
			hs.setCjbh(tmp_id);
			hs.setCombi_id(tmp_Code_t);
			hs.setInvesttype((String) map.get("c_invest_type".toUpperCase()));
			hs.setDirection((String) map.get("VC_report_direction".toUpperCase()));
			hs.setMarket_no((String) map.get("c_market_no".toUpperCase()));
			hs.executeInsert(vbaExtendsService);
		}
	}

	private String getHbywlb(String tmp_MXYWLB, Double mxsfje) {
		if ("JY00".equals(tmp_MXYWLB) || "JY01".equals(tmp_MXYWLB) || "HGCS".equals(tmp_MXYWLB)) {
			return mxsfje > 0 ? "0S" : "0B";
		} else if ("HGDQ".equals(tmp_MXYWLB)) {
			return mxsfje > 0 ? "9S" : "9B";
		}
		return null;
	}

	private String getYwlbQsjs(String tmp_HBYWLB, String pstrSjsRepo, String tmp_HBZQDM, Integer tmp_HBCJSL) {
		String ywlbQsjs = null;
		if (tmp_HBYWLB.indexOf("0B") >= 0) {
			if (pstrSjsRepo.indexOf(tmp_HBZQDM) >= 0) {
				ywlbQsjs = "03";
			} else {
				ywlbQsjs = "01";
			}
		} else if (tmp_HBYWLB.indexOf("0S") >= 0) {
			if (pstrSjsRepo.indexOf(tmp_HBZQDM) >= 0 && tmp_HBCJSL == 0) {
				ywlbQsjs = "04";
			} else {
				ywlbQsjs = "02";
			}
		} else if (tmp_HBYWLB.indexOf("9B") >= 0) {
			ywlbQsjs = "03";
		} else if (tmp_HBYWLB.indexOf("9C") >= 0) {
			ywlbQsjs = "04";
		}
		return ywlbQsjs;
	}
}
